package com.halfsword.creativecraft.integration.jei;

import com.halfsword.creativecraft.CreativeCraft;
import com.halfsword.creativecraft.block.BlockLoader;
import com.halfsword.creativecraft.recipe.SpaceCollectorRecipe;
import mezz.jei.api.constants.VanillaTypes;
import mezz.jei.api.gui.builder.IRecipeLayoutBuilder;
import mezz.jei.api.gui.drawable.IDrawable;
import mezz.jei.api.gui.ingredient.IRecipeSlotsView;
import mezz.jei.api.helpers.IGuiHelper;
import mezz.jei.api.recipe.IFocusGroup;
import mezz.jei.api.recipe.RecipeIngredientRole;
import mezz.jei.api.recipe.RecipeType;
import mezz.jei.api.recipe.category.IRecipeCategory;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import org.checkerframework.checker.units.qual.C;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class SpaceCollectorCategory implements IRecipeCategory<SpaceCollectorRecipe> {

    public static final ResourceLocation UID = ResourceLocation.fromNamespaceAndPath(CreativeCraft.MOD_ID, "space_collector");
    public static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath(CreativeCraft.MOD_ID, "textures/gui/space_collector.png");
    public static final RecipeType<SpaceCollectorRecipe> SPACE_COLLECTOR_TYPE = new RecipeType<>(UID, SpaceCollectorRecipe.class);

    private final IDrawable background;
    private final IDrawable icon;
    private final IGuiHelper guiHelper;
    private final Font font; // 添加字体变量

    // 显式定义尺寸
    private final int width = 155;
    private final int height = 81;

    public SpaceCollectorCategory(IGuiHelper helper) {
        this.guiHelper = helper;
        this.font = Minecraft.getInstance().font; // 初始化字体

        // 创建背景（使用drawableBuilder确保正确尺寸）
        this.background = helper.drawableBuilder(TEXTURE, 0, 0, width, height)
                .setTextureSize(256, 256) // 使用原始纹理尺寸
                .build();

        this.icon = helper.createDrawableIngredient(
                VanillaTypes.ITEM_STACK,
                new ItemStack(BlockLoader.SPACE_SHARD_COLLECTOR_MACHINE.get())
        );
    }

    @Override
    public @NotNull RecipeType<SpaceCollectorRecipe> getRecipeType() {
        return SPACE_COLLECTOR_TYPE;
    }

    @Override
    public @NotNull Component getTitle() {
        return Component.translatable("block.creativecraft.space_collector");
    }

    // 必须覆盖尺寸方法
    @Override
    public int getWidth() {
        return width;
    }

    @Override
    public int getHeight() {
        return height;
    }

    @Override
    public @Nullable IDrawable getIcon() {
        return this.icon;
    }

    @Override
    public void setRecipe(@NotNull IRecipeLayoutBuilder builder, SpaceCollectorRecipe recipe, @NotNull IFocusGroup focuses) {
        // 确保配方有足够的原料（固定4个槽位）
        if (recipe.getIngredients().size() >= 4) {
            builder.addSlot(RecipeIngredientRole.INPUT, 27, 8).addIngredients(recipe.getIngredients().get(0));
            builder.addSlot(RecipeIngredientRole.INPUT, 27, 59).addIngredients(recipe.getIngredients().get(1));
            builder.addSlot(RecipeIngredientRole.INPUT, 57, 16).addIngredients(recipe.getIngredients().get(2));
            builder.addSlot(RecipeIngredientRole.INPUT, 57, 52).addIngredients(recipe.getIngredients().get(3));
        }

        // 添加输出槽
        builder.addSlot(RecipeIngredientRole.OUTPUT, 126, 12).addItemStack(recipe.getResultItem(null));
    }

    // 添加draw方法手动绘制背景
    @Override
    public void draw(SpaceCollectorRecipe recipe, @NotNull IRecipeSlotsView recipeSlotsView, @NotNull GuiGraphics guiGraphics,
                     double mouseX, double mouseY) {

        // 1. 手动绘制背景
        background.draw(guiGraphics, 0, 0);

        // 从 (8, 82) 开始渲染配方信息
        int startX = 0;
        int startY = 90;
        int textColor = 0xFF404040; // 深灰色文本

        // 1. 绘制处理时间（转换为秒）
        float seconds = recipe.getProcessingTime() / 20f;
        MutableComponent timeText = Component.translatable("jei.creativecraft.time", String.format("%.1f", seconds))
                .withStyle(ChatFormatting.DARK_GRAY);
        guiGraphics.drawString(font, timeText, startX, startY, textColor, false);
        startY += 0;
        startX += 100;

        // 2. 绘制维度要求
        ResourceLocation dimension = recipe.getDimension();



        MutableComponent dimNameC = switch (dimension.getPath()) {
            case "overworld" -> Component.translatable("jei.creativecraft.dimension_1");
            case "the_nether" -> Component.translatable("jei.creativecraft.dimension_2");
            case "the_end" -> Component.translatable("jei.creativecraft.dimension_3");
            case "null" -> Component.translatable("jei.creativecraft.dimension_null");
            default -> Component.literal(dimension.getPath());
        };
        MutableComponent dimText = Component.translatable("jei.creativecraft.dimension", dimNameC)
                    .withStyle(ChatFormatting.DARK_GRAY);
            guiGraphics.drawString(font,dimText,startX,startY,textColor,false);
            startY += 10;
            startX -= 100;








        // 3. 绘制高度范围要求
        int minY = recipe.getMinHeight();
        int maxY = recipe.getMaxHeight();

// 检查是否为默认世界高度范围

        if (minY == -64 && maxY == 256) {
            // 创建"无要求"文本组件
            MutableComponent nullRequire =Component.translatable("jei.creativecraft.height.no_requirement");
            MutableComponent heightText = Component.translatable("jei.creativecraft.height",nullRequire)
                    .withStyle(ChatFormatting.DARK_GRAY);
            guiGraphics.drawString(font, heightText, startX, startY, textColor, false);
            startX += 100;  // 水平位置右移
        }
// 检查是否有自定义高度限制
        else if (minY != Integer.MIN_VALUE || maxY != Integer.MAX_VALUE) {
            String heightRange;
            // 生成范围描述文本
            if (minY != Integer.MIN_VALUE && maxY != Integer.MAX_VALUE) {
                heightRange = minY + " - " + maxY;
            }
            else if (minY != Integer.MIN_VALUE) {
                heightRange = "≥ " + minY;
            } else {
                heightRange = "≤ " + maxY;
            }


            // 创建高度范围文本组件
            MutableComponent heightText = Component.translatable("jei.creativecraft.height", heightRange)
                    .withStyle(ChatFormatting.DARK_GRAY);
            guiGraphics.drawString(font, heightText, startX, startY, textColor, false);
            startX += 100;  // 水平位置右移
        }

        // 4. 绘制配方类型（有序/无序）
        String type = recipe.isShapeless() ?
                Component.translatable("jei.creativecraft.shapeless").getString() :
                Component.translatable("jei.creativecraft.shaped").getString();

        MutableComponent typeText = Component.translatable("jei.creativecraft.type", type)
                .withStyle(ChatFormatting.DARK_GRAY);
        guiGraphics.drawString(font, typeText, startX, startY, textColor, false);
    }
}